<template>
  <div class="paper-score-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span>试卷分值管理</span>
          <el-button type="primary" @click="handleAdd">新增试卷分值</el-button>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="考试名称">
          <el-input v-model="searchForm.examName" placeholder="请输入考试名称" clearable />
        </el-form-item>
        <el-form-item label="科目">
          <el-input v-model="searchForm.subject" placeholder="请输入科目" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border stripe v-loading="loading">
        <el-table-column prop="examName" label="考试名称" min-width="150" />
        <el-table-column prop="subject" label="科目" min-width="150" />
        <el-table-column prop="totalQuestions" label="总题量" width="80" />
        <el-table-column prop="totalScore" label="总分值" width="80" />
        <el-table-column prop="totalTime" label="总时长(分钟)" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" @click="handleViewDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />

      <!-- 编辑/新增对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="80%"
        :before-close="handleDialogClose"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="考试名称" prop="examName">
                <el-input v-model="formData.examName" placeholder="请输入考试名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="科目" prop="subject">
                <el-input v-model="formData.subject" placeholder="请输入科目" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="总题量" prop="totalQuestions">
                <el-input-number
                  v-model="formData.totalQuestions"
                  :min="1"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总分值" prop="totalScore">
                <el-input-number
                  v-model="formData.totalScore"
                  :min="1"
                  :precision="1"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="总时长(分钟)" prop="totalTime">
                <el-input-number
                  v-model="formData.totalTime"
                  :min="1"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 详细信息部分 -->
          <el-divider content-position="left">各部分详细信息</el-divider>
          
          <div v-if="formData.details && formData.details.length > 0">
            <el-table :data="formData.details" border style="width: 100%; margin-bottom: 20px;">
              <el-table-column label="部分" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.part" placeholder="请输入部分名称" />
                </template>
              </el-table-column>
              <el-table-column label="题型模块" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.module" placeholder="请输入题型模块" />
                </template>
              </el-table-column>
              <el-table-column label="题量" width="100">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.questionCount"
                    :min="0"
                    controls-position="right"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="分值(每题)" width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.scorePerQuestion"
                    :min="0"
                    :precision="2"
                    controls-position="right"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="总分数" width="120">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.totalScore"
                    :min="0"
                    :precision="1"
                    controls-position="right"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="参考时间(分钟)" width="130">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.referenceTime"
                    :min="0"
                    controls-position="right"
                    style="width: 100%"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button
                    type="danger"
                    size="small"
                    @click="removeDetailRow(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else>
            <p>暂无详细信息</p>
          </div>

          <div style="margin-bottom: 20px;">
            <el-button type="primary" @click="addDetailRow">添加明细</el-button>
          </div>
        </el-form>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="试卷分值详情"
        width="80%"
      >
        <el-descriptions :column="1" border>
          <el-descriptions-item label="考试名称">{{ detailData.examName }}</el-descriptions-item>
          <el-descriptions-item label="科目">{{ detailData.subject }}</el-descriptions-item>
          <el-descriptions-item label="总题量">{{ detailData.totalQuestions }}</el-descriptions-item>
          <el-descriptions-item label="总分值">{{ detailData.totalScore }}</el-descriptions-item>
          <el-descriptions-item label="总时长">{{ detailData.totalTime }}分钟</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">各部分详细信息</el-divider>
        
        <div v-if="detailData.details && detailData.details.length > 0">
          <el-table :data="detailData.details" border stripe>
            <el-table-column prop="part" label="部分" width="120" />
            <el-table-column prop="module" label="题型模块" width="150" />
            <el-table-column prop="questionCount" label="题量" width="100" />
            <el-table-column prop="scorePerQuestion" label="分值(每题)" width="120" />
            <el-table-column prop="totalScore" label="总分数" width="120" />
            <el-table-column prop="referenceTime" label="参考时间(分钟)" width="130" />
          </el-table>
        </div>
        <div v-else>
          <p>暂无详细信息</p>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  getPaperScores, 
  createPaperScore, 
  updatePaperScore, 
  deletePaperScore,
  getPaperScoreById
} from '../../api/paperScore'

// 搜索表单
const searchForm = reactive({
  examName: '',
  subject: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 详情对话框
const detailDialogVisible = ref(false)
const detailData = ref({
  id: 0,
  examName: '',
  subject: '',
  totalQuestions: 0,
  totalScore: 0,
  totalTime: 0,
  details: [] as any[]
})

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = ref({
  id: 0,
  examName: '',
  subject: '',
  totalQuestions: 0,
  totalScore: 0,
  totalTime: 0,
  details: [] as any[]
})

// 表单验证规则
const formRules = reactive<FormRules>({
  examName: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
  subject: [{ required: true, message: '请输入科目', trigger: 'blur' }],
  totalQuestions: [{ required: true, message: '请输入总题量', trigger: 'blur' }],
  totalScore: [{ required: true, message: '请输入总分值', trigger: 'blur' }],
  totalTime: [{ required: true, message: '请输入总时长', trigger: 'blur' }]
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      examName: searchForm.examName,
      subject: searchForm.subject
    }
    const res: any = await getPaperScores(params)
    console.log('试卷分值列表数据:', res) // 调试信息：查看响应数据结构
    // 修复数据结构不匹配的问题
    if (res && res.data) {
      tableData.value = res.data.list || res.data.records || []
      pagination.total = res.data.total || 0
      console.log('表格数据:', tableData.value) // 调试信息：查看处理后的表格数据
      // 检查是否有详情数据
      if (tableData.value.length > 0) {
        console.log('第一条数据的详情:', (tableData.value[0] as any).details)
        // 检查所有数据的详情
        tableData.value.forEach((item: any, index: number) => {
          console.log(`第${index + 1}条数据的详情:`, item.details)
        })
      }
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取试卷分值数据失败:', error) // 调试信息：查看错误详情
    ElMessage.error('获取数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.examName = ''
  searchForm.subject = ''
  pagination.currentPage = 1
  fetchData()
}

// 分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增试卷分值'
  isEdit.value = false
  formData.value = {
    id: 0,
    examName: '',
    subject: '',
    totalQuestions: 0,
    totalScore: 0,
    totalTime: 0,
    details: []
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: any) => {
  dialogTitle.value = '编辑试卷分值'
  isEdit.value = true
  
  try {
    const res: any = await getPaperScoreById(row.id)
    console.log('试卷分值详情数据:', res) // 调试信息：查看详情数据结构
    console.log('编辑时获取的详情数据:', res.data) // 添加调试信息
    if (res.data && res.data.details) {
      console.log('编辑时获取的详情列表:', res.data.details)
      console.log('详情列表长度:', res.data.details.length)
    } else {
      console.log('编辑时未获取到详情数据')
    }
    formData.value = {
      ...res.data,
      // 确保details字段存在且为数组
      details: res.data && res.data.details && Array.isArray(res.data.details) ? res.data.details : []
    }
    console.log('设置到表单的详情数据:', formData.value.details)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取试卷分值详情失败:', error) // 调试信息：查看错误详情
    ElMessage.error('获取详情失败')
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除试卷 "${row.examName}" 的分值配置吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deletePaperScore(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 查看详情
const handleViewDetails = async (row: any) => {
  try {
    const res: any = await getPaperScoreById(row.id)
    console.log('试卷分值详情弹窗数据:', res) // 调试信息：查看详情弹窗数据结构
    console.log('详情数据结构:', res.data) // 调试信息：查看详情数据结构
    if (res.data && res.data.details) {
      console.log('详情列表:', res.data.details)
      console.log('详情列表长度:', res.data.details.length)
    }
    detailData.value = {
      ...res.data,
      // 确保details字段存在且为数组
      details: res.data && res.data.details && Array.isArray(res.data.details) ? res.data.details : []
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取试卷分值详情失败:', error) // 调试信息：查看错误详情
    ElMessage.error('获取详情失败')
  }
}

// 添加明细行
const addDetailRow = () => {
  formData.value.details.push({
    part: '',
    module: '',
    questionCount: 0,
    scorePerQuestion: 0,
    totalScore: 0,
    referenceTime: 0
  })
}

// 删除明细行
const removeDetailRow = (index: number) => {
  formData.value.details.splice(index, 1)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('提交的表单数据:', formData.value) // 调试信息：查看提交的数据
        if (isEdit.value) {
          // 编辑时确保传递完整的数据结构
          const submitData = {
            ...formData.value,
            details: formData.value.details || []
          }
          await updatePaperScore(submitData)
          ElMessage.success('更新成功')
        } else {
          await createPaperScore(formData.value)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('保存试卷分值失败:', error) // 调试信息：查看错误详情
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
      }
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
}

// 初始化数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.paper-score-management {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>